package lc.com.pcsc.utils;

import android.util.Base64;

import java.security.Key;
import java.util.UUID;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

/**
 * Created by Administrator on 2018/1/9.
 */

public class EncodeUtil {

    /**
     * ECB加密,不要IV
     *
     * @param key  密钥
     * @param data 明文
     * @return
     * @throws Exception
     */
    public static byte[] des3EncodeECB(byte[] key, byte[] data) throws Exception {
        byte[] ming ;
        int count = data.length / 8;
        int remain = data.length % 8;
        if (remain == 0){
            ming = new byte[data.length];
        }else{
            ming = new byte[count*8+8];
        }

        System.arraycopy(data, 0, ming, 0, data.length);

        Key desKey;
        DESedeKeySpec spec = new DESedeKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("desede");
        desKey = keyFactory.generateSecret(spec);

        Cipher cipher = Cipher.getInstance("desede/ECB/NoPadding");

        cipher.init(Cipher.ENCRYPT_MODE, desKey);

        return cipher.doFinal(ming);
    }




    /**
     * ECB解密,不要IV
     *
     * @param key  密钥
     * @param data
     * @return 明文
     * @throws Exception
     */
    public static byte[] des3DecodeECB(byte[] key, byte[] data) throws Exception {

        Key desKey;
        DESedeKeySpec spec = new DESedeKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("desede");
        desKey = keyFactory.generateSecret(spec);

        Cipher cipher = Cipher.getInstance("desede" + "/ECB/NoPadding");

        cipher.init(Cipher.DECRYPT_MODE, desKey);

        byte[] bOut = cipher.doFinal(data);

        return bOut;
    }



    /**
     * 字节数组拼接
     *
     * @param bt1
     * @param bt2
     * @return
     */
    public static byte[] byteContact(byte[] bt1, byte[] bt2) {
        if (bt1 == null) {
            return bt2;
        } else {
            byte[] bt3 = new byte[bt1.length + bt2.length];
            System.arraycopy(bt1, 0, bt3, 0, bt1.length);
            System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length);
            return bt3;
        }

    }

}
